package org.beetl.ormunit;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.beetl.sql.core.SQLManager;



public class BeetlSQLMapper implements Mapper {
	Log log = LogFactory.getLog(BeetlSQLMapper.class);	
	SQLManager sqlManager;
	String basePkg;
	String[] searchPkg;
	Map<String,Class> tableMap = new HashMap<String,Class>();
	
	public BeetlSQLMapper(SQLManager sqlManager,String[] searchPkg){
		this.sqlManager = sqlManager;
		this.searchPkg = searchPkg;
	}
	
	@Override
	public String getClassName(String tableName) {
		Class clz = getClassByTableName(tableName);
		if(clz==null){
			throw new RuntimeException("not found "+tableName);
		}
		return clz.getName();
	}
	
	protected Class getClassByTableName(String tableName){
		Class clz = tableMap.get(tableName);
		if(clz!=null){
			return clz;
		}
		String clsName = sqlManager.getNc().getClassName(tableName);
		for(String pkg:searchPkg){
			clz = loadClass(pkg+"."+clsName);
			if(clz!=null){
				tableMap.put(tableName, clz);
			}
			return clz;
		}
		return null;
	}
	
	private Class loadClass(String cls){
		try{
			Class clz =BeetlSQLMapper.class.getClassLoader().loadClass(cls);
			return clz;
		}catch(Exception ex){
			return null;
		}
	}

	@Override
	public String getAttrName(String tableName,String colName) {
		Class clz = tableMap.get(tableName);
		return sqlManager.getNc().getPropertyName(clz, colName);
		
	}
	

	
	
	
	
	
	



	@Override
	public Object mapper(Map<String, Object> src, String tableName)  {
		Class clz = getClassByTableName(tableName);
		Object ins = ClassUtil.newInstance(clz.getName());;
		
	
		try {
			XLSBeanUtil.copyPropesrties(src, ins);
		} catch (Exception e) {
			throw new RuntimeException("tableName "+tableName,e);
		}
		
		return ins;
	}

	@Override
	public Object mapperId(Map<String, Object> src, String tableName) {
		//beetlsql 的主键用本身来表示，而不用额外对象
		
		Object ins = mapper(src,tableName);
		return ins;
		
	}

	@Override
	public List<String> getAttrName(String tableName, List<String> cols) {
		List<String> attrs = new ArrayList<String>(cols.size());
		for(String col:cols){
			attrs.add(getAttrName(tableName,col));
		}
		return attrs;
	}



}
